﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Microsoft.Practices.Unity;
using Vit.Common;
using Vit.Common.Helpers;
using Vit.Common.Extensions;
using Vit.Web.Providers;
using Vit.Web.Models;
using Vit.Web.Mvc.Results;
using Vit.Web.Helpers;

namespace Vit.Web.Mvc.Filters
{
    public class PermissionAuthorizationFilter : IAuthorizationFilter, IMvcFilter
    {
        public PermissionAuthorizationFilter()
        {
        }

        #region IAuthorizationFilter Members

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            var attrs = filterContext.ActionDescriptor.GetCustomAttributes(typeof(AuthorizeAttribute), true);
            if (attrs == null || attrs.Count() == 0)
                attrs = filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(AuthorizeAttribute), true);
            if (attrs != null && attrs.Count() > 0)
            {
                string url = filterContext.HttpContext.Request.Url.AbsolutePath.ToLower();

                if (HttpContext.Current.Request.IsAuthenticated)
                {
                    bool authorized = Unity.Current.ResolveAny<IMembershipProvider>().ForEach<IMembershipProvider, bool>(p => p.CanUserAccess(PortalContext.Current.User.Account, url));
                    if (authorized)
                    {
                        return;
                    }
                }
                else
                {
                    filterContext.Result = new HttpUnauthorizedResult();
                }
                filterContext.Result = new UnauthorizedResult();
            }
        }

        #endregion

        #region IMvcFilter Members

        public bool AllowMultiple
        {
            get { return true; }
        }

        public int Order
        {
            get { return (int)FilterScope.Global; }
        }

        #endregion
    }
}
